package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * The main class for the Server application
 * @author Brian O'Connor, Denis Zgonjanin
 *
 */
public class Server implements Runnable {
	
	ServerSocket serverSocket;
	Socket clientSocket;
	ThreadBuffer buffer;
	
	/**
	 * The main method which runs the server
	 * IMPORTANT - BEFORE SUBMITTING, COMMENT IN THE SETDEAMON() LINE
	 * setDeamon() does not allow console output, which is needed for debugging
	 * @param args
	 */
	public static void main (String[] args){
		Server server = new Server();
		while (true){
			try{
				//server.recieve(server.serverSocket.accept());
				server.clientSocket = server.serverSocket.accept();
				Thread t = new Thread(server);
				
				//TODO enable the next line before submitting!
				//t.setDaemon(true);
				t.start();
			} catch (Exception e){
				System.out.println(e.getMessage());
				System.exit(0);
			}
		}
	}
	
	/**
	 * Server class constructor
	 */
	public Server() {
		//Create 10 empty threads using the Buffer
		this.buffer = new ThreadBuffer(10);
		try {
			serverSocket = new ServerSocket(1026);
		} catch (IOException e) {
			System.out.println(e.getMessage());
			System.exit(-1);
		}
	}
	
	/**
	 * When a request is received, it is sent to the buffer, which then allocates
	 * a free thread to deal with it.
	 */
	public void run() {
		this.buffer.processRequest(clientSocket);
	}

}
